package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.client.AlbumClientFeign;
import com.atguigu.tingshu.album.client.TrackClientFeign;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.search.dao.AlbumInfoDao;
import com.atguigu.tingshu.search.dao.SuggestIndexDao;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserClientFeign;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumInfoDao albumInfoDao;

    // TODO-用异步编排实现存入ES业务
    @Resource
    private AlbumClientFeign albumClientFeign;

    @Resource
    private UserClientFeign userClientFeign;

    @Autowired
    private SuggestIndexDao suggestIndexDao;

    @Resource
    private OrderInfoFeignClient orderInfoFeignClient;
    @Resource
    private TrackClientFeign trackClientFeign;

    /**
     * 写入es
     *
     * @param albumId
     */
    @Override
    public void addAlbumFromMysqlToEs(Long albumId) {
        AlbumInfo albumInfo = albumClientFeign.getAlbumInfo(albumId);
        // 判断
        if (albumInfo == null || albumInfo.getId() == null) {
            return;
        }
        // es实体
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        // es中是否存有
        Optional<AlbumInfoIndex> optional = albumInfoDao.findById(albumId);
        if (optional.isPresent()) {
            // 有
            albumInfoIndex = optional.get();
        }
        // 设置属性
        albumInfoIndex.setId(albumInfo.getId());
        albumInfoIndex.setAlbumTitle(albumInfo.getAlbumTitle());
        albumInfoIndex.setAlbumIntro(albumInfo.getAlbumIntro());
        // 调用Feign查询useName
        UserInfo userInfo = userClientFeign.getUserInfo(albumInfo.getUserId());
        albumInfoIndex.setAnnouncerName(userInfo.getNickname());
        // 专辑信息
        albumInfoIndex.setCoverUrl(albumInfo.getCoverUrl());
        albumInfoIndex.setIncludeTrackCount(albumInfo.getIncludeTrackCount());
        albumInfoIndex.setIsFinished(albumInfo.getIsFinished());
        albumInfoIndex.setPayType(albumInfo.getPayType());
        albumInfoIndex.setCreateTime(new Date());
        // 查询分类，设置分类
        BaseCategoryView categoryView =
                albumClientFeign.getBaseCategoryView(albumInfo.getCategory3Id());
        albumInfoIndex.setCategory1Id(categoryView.getCategory1Id());
        albumInfoIndex.setCategory2Id(categoryView.getCategory2Id());
        albumInfoIndex.setCategory3Id(categoryView.getCategory3Id());
        // 查询标签，设置
        List<AlbumAttributeValue> albumAttributeValueList =
                albumClientFeign.getAlbumAttributeValueList(albumId);
        albumInfoIndex.setAttributeValueIndexList(
                albumAttributeValueList.stream().map(a -> {
                    // es的AttributeValueIndex实体
                    AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                    attributeValueIndex.setAttributeId(a.getAttributeId());
                    attributeValueIndex.setValueId(a.getValueId());
                    return attributeValueIndex;
                }).collect(Collectors.toList())
        );
        // 查询统计，设置
        Map<String, Object> albumStatMap =
                albumClientFeign.getAlbumStatMap(albumId);
        albumInfoIndex.setPlayStatNum(Long.valueOf(
                albumStatMap.get(SystemConstant.ALBUM_STAT_PLAY).toString()));
        albumInfoIndex.setSubscribeStatNum(Long.valueOf(
                albumStatMap.get(SystemConstant.ALBUM_STAT_SUBSCRIBE).toString()));
        albumInfoIndex.setBuyStatNum(Long.valueOf(
                albumStatMap.get(SystemConstant.ALBUM_STAT_BROWSE).toString()));
        albumInfoIndex.setCommentStatNum(Long.valueOf(
                albumStatMap.get(SystemConstant.ALBUM_STAT_COMMENT).toString()));
        // 专辑信息保存进ES
        albumInfoDao.save(albumInfoIndex);
        // 专辑标题提示词保存入es -- 根据搜索匹配条件创建保存
        // 保存标题
        saveSuggestIndex(albumInfoIndex.getAlbumTitle(), albumInfoIndex.getAlbumTitle());
        // 保存内容
        saveSuggestIndex(albumInfoIndex.getAlbumIntro(), albumInfoIndex.getAlbumIntro());
        // 保存作者
        saveSuggestIndex(albumInfoIndex.getAnnouncerName(), albumInfoIndex.getAnnouncerName());
    }


    /**
     * 从es删除专辑
     *
     * @param albumId
     */
    @Override
    public void removeFromEs(Long albumId) {
        albumInfoDao.deleteById(albumId);
    }


    /**
     * 提示词初始化
     *
     * @param suggestInfo
     */
    private void saveSuggestIndex(String suggestInfo, String filed) {
        // 初始化
        SuggestIndex suggestIndex = new SuggestIndex();
        // 属性补全
        suggestIndex.setId(UUID.randomUUID().toString().replace("-", ""));
        suggestIndex.setTitle(filed);
        // 三种搜索方式 - 汉字 拼音 拼音首字母
        suggestIndex.setKeyword(new Completion(new String[]{suggestInfo}));
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(suggestInfo)}));
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(suggestInfo)}));
        // 保存
        suggestIndexDao.save(suggestIndex);
    }


    /**
     * 更新专辑热度值
     *
     * @param orderNo
     */
    @Override
    public void updateHotScore(String orderNo) {
        // 查询订单数据
        OrderInfo orderInfo = orderInfoFeignClient.getOrderInfo(orderNo);
        // 获取订单类型 itemType: 1001-专辑 1002-声音 1003-vip会员
        String itemType = orderInfo.getItemType();
        if (itemType.equals("1003")) {
            // 会员订单无热度值
            return;
        }
        // 查询订单详情
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        // 声明操作订单id
        Long albumId = null;
        // 初始化增加热度值
        Integer score = 0;
        // 计算本次增加的热度值 1001-专辑 1002-声音 1003-vip会员
        if (itemType.equals("1001")) {
            // 整张专辑购买 +100
            score = 100;
            // 获取albumId
            albumId = orderDetailList.get(0).getItemId();
        } else if (itemType.equals("1002")) {
            // 单个声音购买 -- 一个声音 5
            score = orderDetailList.size() * 5;
            // 获取trackId
            Long trackId = orderDetailList.get(0).getItemId();
            // 获取track
            TrackInfo trackInfo = trackClientFeign.getTrackInfoDetail(trackId);
            // 查询albumI并赋值
            albumId = trackInfo.getAlbumId();
        }
        // 查询ES中当前专辑的数据
        AlbumInfoIndex albumInfoIndex = albumInfoDao.findById(albumId).get();
        albumInfoIndex.setHotScore(albumInfoIndex.getHotScore() + score);
        albumInfoIndex.setBuyStatNum(albumInfoIndex.getBuyStatNum() + orderDetailList.size());
        albumInfoDao.save(albumInfoIndex);
    }
}
